﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Telerik.Web.Mvc;

namespace Presentation.Web.Admin.Controllers
{
    [HandleError]
    public class UserController : Infrastructure.Crosscutting.NetFramework.Controllers.BaseController
    {
        Infrastructure.Crosscutting.Authorize.IUserService userService;

        Infrastructure.Crosscutting.Authorize.IRoleService roleService;

        Infrastructure.Crosscutting.Authorize.IUserRoleService userRoleService;

        public UserController(Infrastructure.Crosscutting.NetFramework.IWorkContext work,
            Infrastructure.Crosscutting.Authorize.IUserService user,
            Infrastructure.Crosscutting.Authorize.IRoleService role,
            Infrastructure.Crosscutting.Authorize.IUserRoleService userRole)
            : base(work)
        {
            if (user == null)
            {
                throw new ArgumentNullException("userService is null");
            }
            if (role == null)
            {
                throw new ArgumentNullException("roleService is null");
            }
            if (userRole == null)
            {
                throw new ArgumentNullException("userRoleService is null");
            }
            roleService = role;
            userRoleService = userRole;
            userService = user;
        }

        #region user

        public ViewResult Index()
        {
            var model = this.GetStateTureUser();
            var dto = model.ToDto();
            return View(dto);
        }

        [GridAction]
        public JsonResult AjaxIndex(string searchKey)
        {
            var data = this.GetStateTureUser();
            if (!string.IsNullOrEmpty(searchKey))
            {
                data = data.Where(e => e.UserName.Contains(searchKey.Trim()));
            }
            var dto = data.ToDto();
            var model = new GridModel<Domain.Dto.UserDto>
            {
                Data = dto,
                Total = dto.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [GridAction]
        [HttpPost]
        public JsonResult Delete(int id)
        {
            var model = userService.GetUserModelById(id);
            if (model != null && model.Id > 0)
            {
                userService.Delete(model, this.WorkContext.CurrentUser);
            }
            var data = this.GetStateTureUser();
            var dto = data.ToDto();
            return Json(dto, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult MulDelete(FormCollection del)
        {
            var res = false;
            var message = "";
            var selectedList = del.GetValues("selectRow");
            if (selectedList != null && selectedList.Count() > 0)
            {
                res = userService.Delete(selectedList.ToIntList(), this.WorkContext.CurrentUser);
            }
            //返回空，是为了不再请求数据，因为他自己会重新binding的
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult Add(Domain.Dto.UserDto dto)
        {
            var res = false;
            var message = "";
            if (!string.IsNullOrEmpty(dto.UserName) && !string.IsNullOrEmpty(dto.Pwd))
            {
                dto.AddTime = System.DateTime.Now;
                dto.DepartmentID = 0;
                dto.Guid = Infrastructure.Crosscutting.Comm.Service.GuidService.BuilderGuid();
                dto.IpAddress = Infrastructure.Crosscutting.Comm.Service.StringService.GetRealIP();
                dto.UserType = 0;
                dto.Pwd = Infrastructure.Crosscutting.Comm.Service.StringService.Tomd5(dto.Pwd);

                var userRole = userRoleService.GetDefaultUserRole();
                var entity = dto.ToEntity();
                userService.Add(entity, userRole, this.WorkContext.CurrentUser);
                if (entity.Id > 0)
                {
                    res = true;
                }
                else
                {
                    message = "添加失败了T_T";
                }
            }
            else
            {
                message = "用户名或密码不能为空";
            }
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ViewResult Edit(int id)
        {
            var model = userService.GetUserModelById(id);
            var dto = model.ToDto();
            return View(dto);
        }

        [HttpPost]
        public JsonResult Edit(Domain.Dto.UserDto dto)
        {
            var res = false;
            var message = "";
            if (dto.Id > 0 && !string.IsNullOrEmpty(dto.UserName))
            {
                var model = userService.GetUserModelById(dto.Id);
                model.UserName = dto.UserName;
                model.TrueName = dto.TrueName;
                model.Email = dto.Email;
                model.IsActivity = dto.IsActivity;
                model.Phone = dto.Phone;
                model.Sex = dto.Sex;
                model.SortNum = dto.SortNum;
                model.State = dto.State;
                if (!string.IsNullOrEmpty(dto.Pwd))
                {
                    model.Pwd = Infrastructure.Crosscutting.Comm.Service.StringService.Tomd5(dto.Pwd);
                }
                if (userService.Modify(model, this.WorkContext.CurrentUser))
                {
                    res = true;
                }
                else
                {
                    message = "修改失败了T_T";
                }
            }
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult Search(string term)
        {
            if (!string.IsNullOrEmpty(term))
            {
                var data = this.GetStateTureUser().Where(e => e.UserName.Contains(term.Trim()))
                            .OrderBy(e => e.Id).Take(10)
                            .Select(e => e.UserName);
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
            else
            {
                var data = this.GetStateTureUser().OrderBy(e => e.Id).Take(10)
                            .Select(e => e.UserName);
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region util

        protected IQueryable<Domain.Entity.User> GetStateTureUser()
        {
            var data = userService.GetList().Where(e => e.State == true)
                .OrderByDescending(e => e.AddTime);
            return data;
        }

        #endregion
    }
}
